package kz.simplex.photobox.action;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import kz.simplex.photobox.model.User;
import kz.simplex.photobox.util.HashUtils;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

@Stateful
@Name("forgotPassword")
@Scope(ScopeType.EVENT)
public class ForgotPasswordAction implements ForgotPassword
{
    @Logger 
    private Log log;
    
    @In
    EntityManager entityManager;
    
    private String username;
    private String email;
    private String tempPassword;
    
    @Transactional
    public String resetPassword() {
    	if (getUsername() == null || getEmail() == null) return "failed";
    	User theUser = byUserName(getUsername());
    	if (theUser == null) {
    		FacesMessages.instance().addToControl("resetPassword", "User {0} not exists", getUsername());
    		return "failed";
    	}
    	if (!theUser.getEmail().equalsIgnoreCase(getEmail())) {
    		FacesMessages.instance().addToControl("resetPassword", "Incorrect email address. Please try again.");
    		return "failed";
    	}
    	
    	try {
    		setTempPassword(HashUtils.tempPassword());
    		theUser.setPassword(HashUtils.hash(this.getTempPassword()));
    		entityManager.flush();
    		
    		Events.instance().raiseTransactionSuccessEvent("passwordReset");
    		return "success";
    	} catch(Exception e) {
    		FacesMessages.instance().addToControl("resetPassword", "Reset password failed! Reason : unknown");
    		return "failed";
    	}
    }

    // add additional action methods
    public String getUsername() {
    	return username;
    }
    public void setUsername(String username) {
    	this.username = username;
    }
    
    public String getEmail() {
    	return email;
    }
    public void setEmail(String email) {
    	this.email = email;
    }
    
    public String getTempPassword() {
    	return tempPassword;
    }
    public void setTempPassword(String tempPassword) {
    	this.tempPassword = tempPassword;
    }
    
    protected User byUserName(String username) {
    	try {
    		return (User)entityManager.createQuery("from User u where u.username = :username").setParameter("username", username).getSingleResult();
    	} catch(NoResultException e) {
    		return null;
    	}
    }
    
    @Remove
    @Destroy
    public void destroy() {}
}
